import { defineStore } from 'pinia'
import {ref} from "vue";
import {login_refresh} from "@/axios/login.js"
import {setStorage,getStorage} from "@/stores/storage";

export const tokenStore = defineStore('tokenStore', () => {

  const token = ref(getStorage({name:"token"}))
  const refresh_token =  ref(getStorage({name:"refreshToken"}))
  const setToken = (newToken) => {
    token.value = newToken;
    setStorage({name:"token",val:newToken})
  }

  const setRefreshToken = (newToken) => {
    refresh_token.value = newToken;
    setStorage({name:"refreshToken",val:newToken})

  }

  const refreshNow = async() => {
    let params = {};
    params.refreshToken = getStorage({name:"refreshToken"})
    await login_refresh(params).then(res=>{
      setToken(res.data.access_token)
      setRefreshToken(res.data.refresh_token)
    })
  }

  return { token, refresh_token, setToken, setRefreshToken, refreshNow }
})
